package com.wyd.component.netty.handler;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.wyd.component.netty.constants.Constants;
import com.wyd.component.netty.enums.DeviceMessageType;
import com.wyd.component.netty.message.DeviceBaseMessage;
import com.wyd.component.netty.message.HeartBeatReq;
import com.wyd.component.netty.message.LoginReq;
import com.wyd.component.netty.message.LoginResp;
import com.wyd.redis.RedisUtils;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.MessageToMessageCodec;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import java.util.List;


@Component
@Slf4j
public class MsgConvertHandler extends MessageToMessageCodec<String, DeviceBaseMessage> {

    private static MsgConvertHandler msgConvertHandler;

    @Resource
    RedisUtils redisUtils;

    @PostConstruct
    public void init() {
//        msgConvertHandler.redisUtils = this.redisUtils;
    }

    @Override
    protected void encode(ChannelHandlerContext channelHandlerContext, DeviceBaseMessage msg, List<Object> list) throws Exception {
        String s = JSON.toJSONString(msg);
        list.add(s+ Constants.DELIMITER);
    }

    @Override
    protected void decode(ChannelHandlerContext channelHandlerContext, String msg, List<Object> list) throws Exception {
        log.info("=====decode>>>>>>msg:{}", msg);

        DeviceBaseMessage deviceBaseMessage = JSON.parseObject(msg, new TypeReference<DeviceBaseMessage>() {
        });
        if(deviceBaseMessage.getType()== DeviceMessageType.HEART_BEAT_REQ){
            HeartBeatReq heartBeatReq = JSON.parseObject(msg, new TypeReference<HeartBeatReq>() {
            });
            list.add(heartBeatReq);
        }else if(deviceBaseMessage.getType()== DeviceMessageType.HEART_BEAT_RESP){
            HeartBeatReq heartBeatResp = JSON.parseObject(msg, new TypeReference<HeartBeatReq>() {
            });
            list.add(heartBeatResp);
        }else if(deviceBaseMessage.getType()==DeviceMessageType.LOGIN_REQ){
            LoginReq loginReq=JSON.parseObject(msg, new TypeReference<LoginReq>() {
            });
            list.add(loginReq);
        }else if(deviceBaseMessage.getType()==DeviceMessageType.LOGIN_RESP){
            LoginResp loginResp=JSON.parseObject(msg, new TypeReference<LoginResp>() {
            });
            list.add(loginResp);
        }
    }
}
